package com.yenlien.traceyun.control.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.control.dao.AdvertDao;
import com.yenlien.traceyun.control.entity.Advert;
import com.yenlien.traceyun.control.service.rest.FileRestService;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jialong
 * @date 2021/04/27
 * @description:
 **/
@Service
public class AdvertService {

    @Autowired
    private AdvertDao advertDao;

    @Autowired
    private FileRestService fileRestService;


    public boolean save(Advert advert, List<MultipartFile> files) {
        if ("1".equals(advert.getType()) && files.size() > 0) {
            try {
                advert.setImg(fileRestService.upload(files));
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("上传图片失败");
            }
        }
        Advert result = advertDao.save(advert);
        if (StringUtils.isNotBlank(result.getId()))
            return true;
        else
            return false;
    }

    public boolean save2(Advert advert) {
        Advert result = advertDao.save(advert);
        if (StringUtils.isNotBlank(result.getId()))
            return true;
        else
            return false;
    }

    /**
     * 根据携带的参数查询广告
     *
     * @param advert
     * @return
     */
    public Object findList(Advert advert) {
        JSONObject result = new JSONObject();
        Pageable pageable = PageRequest.of(advert.getPage(), advert.getPageSize(), Sort.Direction.DESC, "createTime");
        Page<Advert> advertPage = advertDao.findAll((Root<Advert> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList();
            if (StringUtils.isNotBlank(advert.getTitle())) {
                list.add(cb.like(root.get("title"), "%" + advert.getTitle() + "%"));
            }
            if (StringUtils.isNotBlank(advert.getSendObjName())) {
                list.add(cb.like(root.get("sendObj"), "%" + advert.getSendObjName() + "%"));
            }
            if (StringUtils.isNotBlank(advert.getType())) {
                list.add(cb.equal(root.get("type"), advert.getType()));
            }
//            if (ObjectUtils.isNotEmpty(advert.getUseStartTime()) && ObjectUtils.isEmpty(advert.getUseEndTime())) {
//                list.add(cb.greaterThanOrEqualTo(root.get("useStartTime"), advert.getUseStartTime()));
//            }
//            if (ObjectUtils.isNotEmpty(advert.getUseEndTime()) && ObjectUtils.isEmpty(advert.getUseStartTime())) {
//                list.add(cb.lessThanOrEqualTo(root.get("useEndTime"), advert.getUseEndTime()));
//            }
//            if (ObjectUtils.isNotEmpty(advert.getUseStartTime()) && ObjectUtils.isNotEmpty(advert.getUseEndTime())) {
//                list.add(cb.greaterThanOrEqualTo(root.get("useStartTime"), advert.getUseStartTime()));
//                list.add(cb.lessThanOrEqualTo(root.get("useEndTime"), advert.getUseEndTime()));
////                list.add(cb.between(root.get("useStartTime"), advert.getUseStartTime(), advert.getUseEndTime()));
////                list.add(cb.between(root.get("useEndTime"), advert.getUseStartTime(), advert.getUseEndTime()));
//            }
            if (StringUtils.isNotBlank(advert.getState())) {
                list.add(cb.equal(root.get("state"), advert.getState()));
            }
            return cb.and(list.toArray(new Predicate[list.size()]));
        }, pageable);
        result.put("code", "200");
        result.put("total", advertPage.getTotalElements());
        result.put("rows", advertPage.getContent());
        return result;
    }


    public void deletes(String[] ids) {
        for (String id : ids) {
            advertDao.deleteById(id);
        }
    }

    public Object findById(String id) {
        return advertDao.findById(id);
    }


    /**
     * 获取最近的一条
     *
     * @param companyId
     * @return
     */
    public Object getAdvert(String companyId) {
        Pageable pageable = PageRequest.of(0, 1, Sort.Direction.DESC, "createTime");
        Page<Advert> adverts = advertDao.findAll((Root<Advert> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList();
            list.add(cb.like(root.get("sendObj"), "%" + companyId + "%"));
            list.add(cb.equal(root.get("state"), "1"));
            return cb.and(list.toArray(new Predicate[list.size()]));
        }, pageable);
        JSONObject result = new JSONObject();
        result.put("code", "200");
        if (adverts.getContent() != null && adverts.getContent().size() > 0) {
            result.put("data", adverts.getContent().get(0));
        } else {
            result.put("data", "");
        }
        return result;
    }


}
